    package com.tledu.web04.listener;

    import com.tledu.web04.model.Student;

    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import javax.servlet.annotation.WebListener;
    import java.io.*;
    import java.util.HashMap;

    @WebListener()
    public class SaveUserListener implements ServletContextListener {
        private final String path = "C:\\Users\\cyrus\\Desktop\\delete\\data";

        @Override
        public void contextInitialized(ServletContextEvent sce) {
            // 容器创建
            // 希望用户注册进来进来之后，能一直保存下来
            // 加载的时候进行初始化
            HashMap<String, Student> map = null;
            try {
                FileInputStream in = new FileInputStream(path);
                ObjectInputStream objectInputStream = new ObjectInputStream(in);
                map = (HashMap<String, Student>) objectInputStream.readObject();
                objectInputStream.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println("容器创建了...");
            if (map == null) {
                map = new HashMap<String, Student>();
            }
            sce.getServletContext().setAttribute("studentData", map);
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // 销毁的时候记录下来
            HashMap<String, Student> map = (HashMap<String, Student>) sce.getServletContext().getAttribute("studentData");
            // 序列化
            try {
                FileOutputStream out = new FileOutputStream(path);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
                objectOutputStream.writeObject(map);
                objectOutputStream.flush();
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 容器销毁
            System.out.println("容器销毁了...");
        }
    }
